package com.filesystem.config;



import com.filesystem.shiro.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Shiro 配置类
 * @author JayZhou
 */

@Configuration
public class ShiroConfig {
    /**
     * 创建 ShiroFilterFactoryBean
     */
    @Bean( name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager ){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /*
         * anon：无需认证就可以访问
         * authc：必须认证了才能访问
         * user：必须用有了 记住我 功能才能用
         * perms：拥有对某个资源的权限才能访问
         * role：拥有某个角色权限才能访问
         */
        //未登录跳转
        shiroFilterFactoryBean.setLoginUrl("/login");
        Map<String,String> fileMap = new LinkedHashMap<>();
        fileMap.put("/login","anon");
        fileMap.put("/index","anon");
        //首页文件访问接口
        fileMap.put("/filesList/fileList","anon");
        //首页查询接口
        fileMap.put("/filesList/select","anon");
        fileMap.put("/static/**", "anon");
        //admin目录禁止访问
        fileMap.put("/admin/**","authc");
        //所有接口禁止访问
        fileMap.put("/files/*","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fileMap);
        return shiroFilterFactoryBean;
    }


    /**
     * 创建DefaultWebSecurityManager
     * @Qualifier 找到userRealm
     */
    @Bean( name = "securityManager")
    public DefaultWebSecurityManager getdefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm ){
        //new 一个 DefaultWebSecurityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联 Realm
        securityManager.setRealm(userRealm);
        return  securityManager;
    }



    /**
     * 创建Realm
     * //注解加入spring中
     */
    @Bean
    public UserRealm getRealm(){
        return new UserRealm();
    }

}